package myweb

import (
	"bytes"
	"encoding/json"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"log"
	"main/myimage"
	"main/toolCode"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"golang.org/x/image/draw"
)

func stringProcess(str string, start string, end string) string {
	m := strings.Index(str, start)
	s := str[m+len(start)+4:]
	n := strings.Index(s, end)
	return s[:n]
}

func fileProcess(b []byte) (string, int, int) {
	var img image.Image

	s := string(b)

	m := strings.Index(s, "\r\n\r\n")
	s1 := s[m+4:]
	n := strings.Index(s1, "\r\n------")
	fileData := s1[:n]

	ratio, err := strconv.Atoi(stringProcess(s, `name="ratio"`, "\r\n------"))
	if err != nil {
		log.Println("err:", err)
	}

	fileBytes := []byte(fileData)

	// 使用 bytes.NewReader 将二进制数据转换为 io.Reader
	reader := bytes.NewReader(fileBytes)

	// 解码图像并检查格式
	_, format, err := image.Decode(reader)
	if err != nil {
		log.Fatalf("无法解码图像: %v", err)
	}

	fmt.Println(format)

	reader.Seek(0, 0)

	if format == "png" {
		// 解码PNG图片
		img, err = png.Decode(reader)
		if err != nil {
			log.Printf("Failed to decode PNG: %v", err)
		}
	} else if format == "jpeg" {
		// 解码JPEG图片
		img, err = jpeg.Decode(reader)
		if err != nil {
			log.Printf("Failed to decode JPEG: %v", err)
		}
	}

	// 计算新的宽度和高度，保持比例
	originalHeight := img.Bounds().Dx()
	originalWidth := img.Bounds().Dy()

	fmt.Println(originalWidth, originalHeight)

	height := int(float64(ratio) * float64(originalHeight) / 100)
	width := int(float64(ratio) * float64(originalWidth) / 100)

	// 调整图片大小
	newImg := image.NewRGBA(image.Rect(0, 0, height, width))
	draw.CatmullRom.Scale(newImg, newImg.Bounds(), img, img.Bounds(), draw.Over, nil)

	bPicData := myimage.Rgb888_to_rgb565(newImg, true, 1)

	str := "const unsigned char gImage_pic[] = {\r\n"
	str += fmt.Sprintf("/*width: %d, height: %d */\r\n", width, height)

	for i := 0; i < len(bPicData)-1; i++ {
		str += fmt.Sprintf("0x%02x,", bPicData[i])
		if (i+1)%15 == 0 {
			str += "\r\n"
		}
	}
	str += fmt.Sprintf("0x%02x", bPicData[len(bPicData)-1])
	str += "};"

	return str, width, height
}

func img2bin(r *gin.Engine) {
	r.GET("/img2bin", func(c *gin.Context) {
		c.HTML(http.StatusOK, "img2bin.html", gin.H{
			"title": "hello Go",
		})
	})
	r.POST("/img2binPost", func(c *gin.Context) {
		b, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			fmt.Print(err)
			c.Status(http.StatusInternalServerError) // 返回500状态码
			return
		}

		s, width, height := fileProcess(b)
		fmt.Println(width, height)

		// // 创建输出文件
		// outFile, err := os.Create("resized_example.png")
		// if err != nil {
		// 	panic(err)
		// }
		// defer outFile.Close()

		// // 将新的图片编码为PNG格式并写入文件
		// err = png.Encode(outFile, newImg)
		// if err != nil {
		// 	panic(err)
		// }

		c.JSON(200, gin.H{
			"message": s,
		})
	})
}

func deleteNote(r *gin.Engine) {
	r.GET("/delete_note", func(c *gin.Context) {
		c.HTML(http.StatusOK, "delete_note.html", gin.H{
			"title": "hello Go",
		})
	})
	r.POST("/deleteNotePost", func(c *gin.Context) {
		b, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			fmt.Print(err)
			c.Status(http.StatusInternalServerError) // 返回500状态码
			return
		}
		s := toolCode.Delete_note(string(b))
		fmt.Println(s)
		c.String(http.StatusOK, s)
	})

}

func ttf2bin(r *gin.Engine) {
	r.GET("/ttf2bin", func(c *gin.Context) {
		c.HTML(http.StatusOK, "ttf2bin.html", gin.H{
			"title": "hello Go",
		})
	})
	r.POST("/ttfPost", func(c *gin.Context) {
		b, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			fmt.Print(err)
			c.Status(http.StatusInternalServerError) // 返回500状态码
			return
		}

		s := string(b)

		m := strings.Index(s, "\r\n\r\n")
		s1 := s[m+4:]
		n := strings.Index(s1, "\r\n------")
		fileData := s1[:n]
		err = ioutil.WriteFile("font/font.ttf", []byte(fileData), 0644)

		c.JSON(200, gin.H{
			"message": "",
		})
	})

	r.POST("/ttfSendString", func(c *gin.Context) {
		b, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			fmt.Print(err)
			c.Status(http.StatusInternalServerError) // 返回500状态码
			return
		}
		myimage.Set_ttf("font/font.ttf")

		type ttfType struct {
			Str             string `json:"str"`
			Size            int    `json:"size"`
			ForegroundColor string `json:"foregroundColor"`
			BackgroundColor string `json:"backgroundColor"`
		}

		var ttf ttfType
		err = json.Unmarshal(b, &ttf)
		if err != nil {
			fmt.Println(err)
			return
		}

		name := ""

		str := myimage.Generate_string(ttf.Str, ttf.Size, ttf.ForegroundColor, ttf.BackgroundColor, false, name)
		c.String(http.StatusOK, str)
	})
}

func file2hex(r *gin.Engine) {
	r.GET("/file2hex", func(c *gin.Context) {
		c.HTML(http.StatusOK, "file2hex.html", gin.H{
			"title": "hello Go",
		})
	})

	r.POST("/file2hexpost", func(c *gin.Context) {
		b, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			fmt.Print(err)
		}
		fmt.Println(b)
		c.JSON(200, gin.H{
			"message": " ",
		})
	})
}

func GinInit(ws string) {
	r := gin.Default()
	r.Static("/layui", "./myweb/layui")
	r.Static("/static", "./myweb/static")
	r.StaticFile("img/favicon.ico", "myweb/view/favicon.ico")
	r.LoadHTMLGlob("myweb/view/*")
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "hello Go",
		})
	})

	img2bin(r)
	deleteNote(r)
	ttf2bin(r)
	file2hex(r)
	echatsData(r, ws)
	serialWeb(r, ws)

	r.GET("/ws", wsHandler)
	r.Run(":8080")
	// go broadcastHandler()
}
